﻿using System;
using System.Collections.Generic;
using Common.Logging;

namespace Cactussoft.Common.Logging
{
    public static class LoggerFactory
    {
        private static readonly Dictionary<string, ILogger> loggers = new Dictionary<string, ILogger>();

        public static ILogger Get(Type type)
        {
            ILogger logger;

            if (!loggers.TryGetValue(type.ToString(), out logger))
            {
                try
                {
                    logger = new CommonLoggingLogger(LogManager.GetLogger(type));
                }
                catch (Exception ex)
                {
                    //For some reason log can't be created. Return a stub.
                    logger = new TraceLogger();
                    logger.Error("Unable to create CommonLoggingLogger!", ex);
                }

                loggers.Add(type.ToString(), logger);
            }

            return logger;
        }

        public static ILogger Get(String name)
        {
            ILogger logger;

            if (!loggers.TryGetValue(name, out logger))
            {
                logger = new CommonLoggingLogger(LogManager.GetLogger(name));
                loggers.Add(name, logger);
            }

            return logger;
        }
    }
}
